import React from 'react';
import { NavLink, Link } from 'react-router-dom';
import { Button, Form, Input, Row, Col, Icon } from 'antd';
import { getStuLoginValidCode, studentLogin, getLoginSmsCode } from '../api';
import http from 'libs/http';
import * as utils from 'libs/utils';

const ButtonGroup = Button.Group;
const FormItem = Form.Item;

class StudentLogin extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      validCodeImg: '',
      seconds: '获取验证码',
      mobilePhoneValidCodeFlag: true,
      showErr: false,
      errMessage: '',
      authority: '',
    };
  }

  componentDidMount() {
    // this.checkRoleType()
    this.getStuLoginValidCode();
  }

  checkRoleType = () => {
    http.get('/role/getRole').then(res => {
      res.data && this.setState({
        authority: res.data
      })
    })
  }

  getStuLoginValidCode = () => {
    getStuLoginValidCode((res) => {
      this.setState({
        validCodeImg: res.data,
      });
    });
  }

  // 自定义手机号校验
  validatePhone = (rule, value, callback) => {
    const seconds = this.state.seconds;
    if (!value) {
      callback('手机号不能为空');
    } else if (value && !/^1([38]\d|5[0-35-9]|7[3678])\d{8}$/.test(value)) {
      this.setState({
        mobilePhoneValidCodeFlag: true,
      });
      callback('请输入正确的11位手机号');
    } else {
      http.get('/student/common/validMobile', { mobile: value }).then(res => {
        if (!res.data) {
          callback(<div>该手机号尚未注册，请前去<Link to="/student/register">注册</Link></div>);
        } else {
          this.setState({
            mobilePhoneValidCodeFlag: typeof seconds !== 'string',
          });
          callback();
        }
      })
    }
  }

   // 获取手机验证码
   getLoginSmsCode = () => {
     const form = this.props.form;
     const mobilePhone = form.getFieldValue('mobilePhone');
     let timer = null;
     this.setState({
       seconds: 120,
       mobilePhoneValidCodeFlag: true,
     }, () => {
       getLoginSmsCode({ mobilePhone }, () => {
         timer = setInterval(() => {
           if (this.state.seconds === 0) {
             this.setState({
               seconds: '重新获取',
               mobilePhoneValidCodeFlag: false,
             });
             clearInterval(timer);
             timer = null;
             return;
           }
           this.setState(prevState => ({ seconds: prevState.seconds - 1 }));
         }, 1000);
       }, () => {
         setTimeout(() => {
           this.setState({
             seconds: '重新获取',
             mobilePhoneValidCodeFlag: false,
           });
         }, 1000);
       });
     });
   }

  handleSubmit = (e) => {
    e.preventDefault();
    const { form } = this.props;
    form.validateFields((err, values) => {
      const { mobilePhone, mobileCode, validCode } = values;
      if (!err) {
        studentLogin({
          mobilePhone, mobileCode, validCode, type: 0,
        }, (res) => {
          this.props.history.push('/student_center');
        }, (err) => {
          if(err.code == 6){
            form.setFields({
              validCode: {
                value: '',
                errors: [new Error(err.msg)],
              }
            })
          }else if(err.code == 8){
            form.setFields({
              mobileCode: {
                value: '',
                errors: [new Error(err.msg)],
              }
            });
          }
          this.setState({
            showErr: true,
            errMessage: utils.studentTransformErr(err),
          });
          this.getStuLoginValidCode();
        });
      }
    });
  }

  render() {
    const {
      validCodeImg, mobilePhoneValidCodeFlag, seconds, showErr, errMessage,
    } = this.state;
    const { getFieldDecorator } = this.props.form;
    return (
      <div className="student-form">
        {/* <ButtonGroup className="btn-group">
          <NavLink className="btn-item" to="/student/password_login">
            <Button className="login" style={{ background: '#fff', color: '#00284a', borderRadius: '5px 0 0 5px' }}>密码登录</Button>
          </NavLink>
          <NavLink className="btn-item" to="/student/sms_login">
            <Button className="login" style={{ background: '#00284a', color: '#fff', borderRadius: '0 5px 5px 0' }}>短信登录</Button>
          </NavLink>
        </ButtonGroup> */}
        <Link to="/home" className="close"></Link>
        <div className="login-header">
          <NavLink className="btn-item" to="/student/password_login"><span>密码登录</span></NavLink>
          <NavLink className="btn-item" to="/student/sms_login"><span>短信登录</span></NavLink>
        </div>

        <Form layout="vertical" hideRequiredMark className="login-form" onSubmit={this.handleSubmit} onKeyDown={(e) => { if (e.keyCode == 13) { e.preventDefault(); } }}>
          <FormItem className="label" style={{ marginBottom: 0, height: 64 }}>
            {getFieldDecorator('mobilePhone', {
              rules: [
                { required: true, message: ' ' },
                { validator: this.validatePhone },
              ],
            })(<p><Input 
              size="large"
              prefix={<Icon type="mobile" style={{ color: '#bbb', fontSize: 18 }} />}
              placeholder="请输入11位有效手机号码" autoComplete="off" /></p>)}
          </FormItem>
          <FormItem className="label" style={{ marginBottom: 0, height: 64 }}>
            <Row gutter={16}>
              <Col span={16}>
                {getFieldDecorator('validCode', {
                  rules: [
                    { required: true, message: '验证码不能为空' },
                  ],
                })(<p><Input 
                  size="large"
                  prefix={<Icon type="safety" style={{ color: '#bbb', fontSize: 18 }} />}
                  placeholder="请输入验证码" autoComplete="off" /></p>)}
              </Col>
              <Col span={6} onClick={this.getStuLoginValidCode}>
                <img style={{ width: 100, height: 40, cursor: 'pointer' }} src={validCodeImg} alt="" />
              </Col>
            </Row>
          </FormItem>
          <FormItem style={{ marginBottom: 0, height: 64 }}>
            <Row gutter={16}>
              <Col span={16}>
                {getFieldDecorator('mobileCode', {
                  rules: [
                    { required: true, message: '手机验证码不能为空' },
                  ],
                })(<p><Input 
                  size="large"
                  prefix={<Icon type="safety" style={{ color: '#bbb', fontSize: 18 }} />}
                  placeholder="请输入6位手机验证码" autoComplete="off" /></p>)}
              </Col>
              <Col span={6}>
                <Button
                  style={{ width: 100, height: 40, borderRadius: 2 }}
                  type="primary"
                  disabled={mobilePhoneValidCodeFlag}
                  onClick={this.getLoginSmsCode}
                >{seconds}
                </Button>
              </Col>
            </Row>
          </FormItem>
          
          <Button type="primary" className="btn" htmlType="submit">登录</Button>
          <span className="link-to">
            <span>还没有账号？请</span>
            <NavLink to="/student/register">立即注册</NavLink>
          </span>
        </Form>
      </div>
    );
  }
}

const WrapStudentLogin = Form.create()(StudentLogin);

export default WrapStudentLogin

// <p style={{ 
//   width: '100%',
//   height: 20,
//   color: 'red', 
//   textIndent: 8, 
//   fontSize: 14, 
//   visibility: `${showErr ? true : false}`,
// }}
// >{errMessage}
// </p>